//
//  DriverEditVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/8/6.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "DriverEditVC.h"
#import "DriverMainModel.h"
#import "DriverEditCell.h"

@interface DriverEditVC ()<UITableViewDelegate,UITableViewDataSource> {
    BOOL isAllSelected;
    int page;
}

@property (nonatomic, strong) NSMutableArray <DriverMainModel *>*array;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *allBtn;

@end

@implementation DriverEditVC

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 70, ScreenW, 70 + BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        self.allBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 23, 55, 24)];
        [self.allBtn setTitle:@"全选" forState:0];
        [self.allBtn setTitleColor:HexColor(0x2B2C44) forState:0];
        self.allBtn.titleLabel.font = BoldFontOfSize(14);
        [self.allBtn addTarget:self action:@selector(allClick) forControlEvents:UIControlEventTouchUpInside];
        [self.allBtn setImage:[UIImage imageNamed:@"icon_backBox_choice"] forState:0];
        self.allBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -4, 0, 0);
        [_bottomView addSubview:self.allBtn];
        
        UIButton *stopBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenW - 15 - 68, 20, 68, 30)];
        [stopBtn setBackgroundColor:HexColor(0xF35959)];
        stopBtn.layer.masksToBounds = YES;
        stopBtn.layer.cornerRadius = 15;
        [stopBtn setTitle:@"禁用" forState:0];
        [stopBtn setTitleColor:HexColor(0xffffff) forState:0];
        stopBtn.titleLabel.font = BoldFontOfSize(14);
        [stopBtn addTarget:self action:@selector(stopClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:stopBtn];
        
        UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenW - 15 - 68 - 10 - 68, 20, 68, 30)];
        [deleteBtn setBackgroundColor:Color_ThemeColor];
        deleteBtn.layer.masksToBounds = YES;
        deleteBtn.layer.cornerRadius = 15;
        [deleteBtn setTitle:@"启用" forState:0];
        [deleteBtn setTitleColor:HexColor(0xffffff) forState:0];
        deleteBtn.titleLabel.font = BoldFontOfSize(14);
        [deleteBtn addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:deleteBtn];
        
        UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(deleteBtn.nim_left - 10 - 96, 20, 96, 30)];
        [cancleBtn setBackgroundColor:HexColor(0xF7F7FA)];
        cancleBtn.layer.masksToBounds = YES;
        cancleBtn.layer.cornerRadius = 15;
        [cancleBtn setTitle:@"取消操作" forState:0];
        [cancleBtn setTitleColor:HexColor(0x585974) forState:0];
        cancleBtn.titleLabel.font = BoldFontOfSize(14);
        [cancleBtn addTarget:self action:@selector(cancleClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:cancleBtn];
    }
    return _bottomView;
}

- (void)deleteClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定启用？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForDeleteOrJinYong:1];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

//2=禁用，1=启用
- (void)requestForDeleteOrJinYong:(int)type {
    NSMutableString *str = [NSMutableString stringWithString:@""];
    [self.array enumerateObjectsUsingBlock:^(DriverMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            [str appendFormat:@"%@,",obj.Id];
        }
    }];
    if (str.length) {
        [str deleteCharactersInRange:NSMakeRange(str.length - 1, 1)];
    }
    //1=启用，2=禁用
    [HttpRequest PostWithApi:LogisticsSupplierDriverOperation_V_1_0 params:@{@"ids":str,@"status":@(type)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:type == 1 ? @"已启用" : @"已禁用" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)stopClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定禁用？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForDeleteOrJinYong:2];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)cancleClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

- (void)allClick {
    if (isAllSelected) {
        isAllSelected = NO;
        [self.allBtn setImage:[UIImage imageNamed:@"icon_backBox_choice"] forState:0];
        [self.array enumerateObjectsUsingBlock:^(DriverMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = NO;
        }];
        [self.tableView reloadData];
    }else {
        isAllSelected = YES;
        [self.allBtn setImage:[UIImage imageNamed:@"icon_choice_sel"] forState:0];
        [self.array enumerateObjectsUsingBlock:^(DriverMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = YES;
        }];
        [self.tableView reloadData];
    }
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - BottomHeight - 64 - NaviHeight)];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
//        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            __strong_self;
//            strongSelf->page = 1;
//            [strongSelf requestForList];
//        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
    }
    return _tableView;
}

-(NSMutableArray<DriverMainModel *> *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"司机管理";
    page = 1;
    isAllSelected = NO;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self requestForList];
}

- (void)requestForList {
    [HttpRequest PostWithApi:LogisticsSupplierDriverList_V_1_0 params:@{@"page":@(page)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.array removeAllObjects];
                self.array = [DriverMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [DriverMainModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.array addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DriverEditCell *cell = [DriverEditCell DriverEditCellWithTableView:tableView];
    DriverMainModel *model = self.array[indexPath.row];
    cell.model = model;
    cell.chooseBlock = ^{
        model.isSelected = !model.isSelected;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DriverEditCell *cell = [DriverEditCell DriverEditCellWithTableView:tableView];
    return cell.height;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
